﻿using System.Net.Mail;
using System.Configuration;
using System.Text;
using System.Net;
using webapi.Controllers;

namespace webapi.Helper
{
    public class EmailHelper
    {
        private string smtpServer = "smtp.163.com";
        private string fromEmail = "18758370031@163.com";
        private string smtpUsername = "star graph";
        private string smtpPassword = "UZTAYDBAFSFXJJAC";

        public ConfigurationManager _configurationManager { get; set; }
        private readonly ILogger<SampleController> _logger;

        public EmailHelper()
        {
            _configurationManager = new ConfigurationManager();
        }

        public void SendMessage(string toEmailAdress, string verifyCode)
        {
            string subject = "[NoReply]XYC Registration verification:";
            string body = $"<html>\r\n<head>\r\n</head>\r\n\t<body>\r\n\t\t<p>\r\n\t\t\t<p style= 'display: inline-block;font-family: Arial;font-size: 16pt;'>\r\n\t\t\t\tPlease enter the following verification code within 10 minutes:&nbsp\r\n\t\t\t</p>\r\n\t\t\t<p style='font-family: Arial; color: #000000; font-size: 24pt;display: inline-block'>\r\n\t\t\t{verifyCode}\r\n\t\t\t</p>\r\n\t\t</p>\r\n\t</body>\r\n</html>";

            using (SmtpClient smtpClient = new SmtpClient(smtpServer))
            {
                MailAddress from = new MailAddress(fromEmail, smtpUsername, Encoding.UTF8);
                MailAddress to = new MailAddress(toEmailAdress);
                MailMessage message = new MailMessage(from, to);

                message.Subject = subject;
                message.Body = body;

                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.EnableSsl = true;

                NetworkCredential networkCredential = new NetworkCredential(fromEmail, smtpPassword);
                smtpClient.Credentials = networkCredential;

                try
                {
                    smtpClient.Send(message);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
            }
        }
    }
}
